import {
  ControllerEvent,
  EditorController,
  EventBase,
  FormItemController,
  getDeACMode,
} from '@ibiz-template/runtime';
import { IAppDEACMode, IDEACModeDataItem, IPicker } from '@ibiz/model-core';
import { IHttpResponse, RuntimeModelError } from '@ibiz-template/core';
import { ICheckinHolidayCalendarEvent } from './checkin-holiday-calendar.event';

export class CheckinHolidayCalendarController extends EditorController<IPicker> {
  /**
   * 节假日信息
   *
   * @type {IData[]}
   */
  public items: IData[] = [];

  /**
   * 自填模式sort排序
   */
  public sort: string | undefined = '';

  /**
   * 实体自填模式模型
   */
  public deACMode: IAppDEACMode | undefined = undefined;

  /**
   * 数据集codeName
   */
  public interfaceName: string = '';

  /**
   * 主键属性名称
   */
  public keyName: string = 'srfkey';

  /**
   * 主文本属性名称
   */
  public textName: string = 'srfmajortext';

  /**
   * 自填数据项集合（已排除了value和text)
   */
  public dataItems: IDEACModeDataItem[] = [];

  public evt: ControllerEvent<ICheckinHolidayCalendarEvent> =
    new ControllerEvent<ICheckinHolidayCalendarEvent>(
      this.getEventArgs.bind(this),
    );

  protected getEventArgs(): Omit<EventBase, 'eventName'> {
    return {
      context: this.context,
      params: this.params,
      data: [],
      eventArg: '',
      targetName: this.model.name!,
      view: this.view,
    };
  }

  /**
   * 日期
   *
   * @type {string}
   * @memberof CustomHolidaysCalendarController
   */
  public rq: string = '';

  protected async onInit(): Promise<void> {
    super.onInit();
    // this.valueItem = this.model.valueItemName?.toLowerCase() || '';
    if (this.model.appDataEntityId) {
      if (this.model.appDEDataSetId) {
        this.interfaceName = this.model.appDEDataSetId;
      }
      if (this.model.appDEACModeId) {
        this.deACMode = await getDeACMode(
          this.model.appDEACModeId,
          this.model.appDataEntityId,
          this.context.srfappid,
        );
        if (this.deACMode) {
          // 自填模式相关
          const { minorSortAppDEFieldId, minorSortDir } = this.deACMode;
          if (minorSortAppDEFieldId && minorSortDir) {
            this.sort = `${minorSortAppDEFieldId.toLowerCase()},${minorSortDir.toLowerCase()}`;
          }
          if (this.deACMode.textAppDEFieldId) {
            this.textName = this.deACMode.textAppDEFieldId;
          }
          if (this.deACMode.valueAppDEFieldId) {
            this.keyName = this.deACMode.valueAppDEFieldId;
          }
          if (this.deACMode.deacmodeDataItems) {
            this.dataItems = [];
            this.deACMode.deacmodeDataItems.forEach(
              (dataItem: IDEACModeDataItem) => {
                if (dataItem.id !== 'value' && dataItem.id !== 'text') {
                  this.dataItems.push(dataItem);
                }
              },
            );
          }
        }
      }
    }
  }

  /**
   * 刷新数据
   *
   * @memberof CustomHolidaysCalendarController
   */
  async refresh(): Promise<void> {
    const result = await this.getServiceData(
      '',
      (this.parent as FormItemController).form.data,
    );

    this.items = result.data;

    this.evt.emit('onChange', { data: this.items });
  }

  public async getServiceData(
    query: string,
    data: IData,
  ): Promise<IHttpResponse<IData[]>> {
    // 附加编辑器视图参数
    const tempParams = { ...this.params };
    if (this.sort && !Object.is(this.sort, '')) {
      Object.assign(tempParams, { sort: this.sort });
    }
    Object.assign(tempParams, { query, size: 1000 });

    const { context, params } = this.handlePublicParams(
      data,
      this.context,
      tempParams,
    );

    const workService = await ibiz.hub.getAppDEService(
      context.srfappid,
      'attendanceapp.attendance_workday',
      context,
    );
    const shiftService = await ibiz.hub.getAppDEService(
      context.srfappid,
      'attendanceapp.attendance_shift',
      context,
    );

    const workdays = await workService.local.getList();
    const shifts = await shiftService.local.getList();

    Object.assign(params, {
      rq: this.rq,
      holiday: data.holiday,
      inversion_cycle: data.inversion_cycle,
      inversion_count: data.inversion_count,
      same_restday: data.same_restday,
      inversion_days: data.inversion_days,
      rest: data.rest,
      work: data.work,
      schedule_type: data.schedule_type,
      biweekly_cycle: data.biweekly_cycle,
      workdays,
      shifts,
    });
    if (this.interfaceName) {
      const app = ibiz.hub.getApp(ibiz.env.appId);
      const res = await app.deService.exec(
        this.model.appDataEntityId!,
        this.interfaceName,
        context,
        params,
      );
      return res as IHttpResponse<IData[]>;
    }
    throw new RuntimeModelError(this.model, '请配置实体和实体数据集');
  }
}
